import {ipcRenderer, IpcRendererEvent, webUtils,} from "electron";
import {getId} from "../common/util/idUtl"; // import { electronAPI } from '@electron-toolkit/preload'
// import { electronAPI } from '@electron-toolkit/preload'
import {setApi} from "./base";

// Custom APIs for renderer
const api = {
  selectFile: () => {
    ipcRenderer.send("selectFile");
  },
  selectFileByWjj: () => {
    ipcRenderer.send("selectFileByWjj");
  },
  getPrinters: () => {
    return ipcRenderer.sendSync("getPrinters");
  },
  print: (option) => {
    return new Promise((resolve, reject) => {
      const id = getId()
      ipcRenderer.once("result" + id, (event, errmsg) => {
        if (errmsg) {
          reject(errmsg)
        } else {
          resolve(null)
        }
      })
      ipcRenderer.send("print", {
        id,
        ...option
      });
    })
  },
  openSetting: () => {
    ipcRenderer.send("openSetting");
  },
  showMessage: (option) => {
    return new Promise((resolve, reject) => {
      const id = getId()
      ipcRenderer.once("result" + id, (e, res) => {
        resolve(res)
      })
      ipcRenderer.send("showMessage", {id, ...option});
    })
  },
  on: (
    channel: string,
    listener: (event: IpcRendererEvent, ...args: any[]) => void,
  ) => {
    ipcRenderer.removeAllListeners(channel)
    ipcRenderer.on(channel, listener);
  },
  getPathForFile: (file) => {
    return webUtils.getPathForFile(file);
  },
  addItems: (pathList) => {
    ipcRenderer.send("addItems", pathList);
  },
  preview: (path) => {
    ipcRenderer.send("preview", path);
  },
  showContextMenu: (option) => {
    const id = getId()
    for (let optionElement of option) {
      if (optionElement.click) {
        ipcRenderer.once(optionElement.label + id, optionElement.click)
        delete optionElement.click
      }
    }
    ipcRenderer.send('show-context-menu', {id, option})
  },
  getPrintCount: (): number => {
    return ipcRenderer.sendSync("getPrintCount");
  },
  addPrintCount: (count: number): void => {
    ipcRenderer.send("addPrintCount", count);
  },
  getAppInfo: (): void => {
    return ipcRenderer.sendSync("getAppInfo");
  },
  getPrintFile: (path) => {
    return new Promise((resolve, reject) => {
      const id = getId()
      ipcRenderer.once("result" + id, (e, {error, printFile}) => {
        if (error) {
          return reject(error)
        }
        resolve(printFile)
      })
      ipcRenderer.send("getPrintFile", {id, path});
    })
  },
};

setApi(api)